package com.hzhr.iot.login.service;

import com.hzhr.iot.core.constant.CommonOptions;
import com.hzhr.iot.core.exception.ServiceException;
import com.hzhr.iot.core.util.HzhrDateUtil;
import com.hzhr.iot.core.util.HzhrStringUtils;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.login.Global;
import com.hzhr.iot.login.constant.Login_ErrorsEnum;
import com.hzhr.iot.login.dao.UserCardDao;
import com.hzhr.iot.login.dao.mapper.generator.UserEntityMapper;
import com.hzhr.iot.login.entity.UserCardEntity;
import com.hzhr.iot.login.entity.UserEntity;
import com.hzhr.iot.login.entity.UserEntityExample;
import com.hzhr.iot.login.model.token.TokenModel;
import com.hzhr.iot.login.service.base.BaseService;
import com.hzhr.iot.login.util.RedisUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class TokenService extends BaseService {
    @Autowired
    UserCardService userCardService;
    @Autowired
    UserCardDao userCardDao;
    @Autowired
    HttpServletRequest request;
    @Autowired
    Global global;
    @Autowired
    UserEntityMapper userEntityMapper;
    @Autowired
    RedisUtil redisUtil;

    //region javadoc注释 : get
    /**
     * 获取用户的登录令牌 <br/><br/>
     * 简介&nbsp;:&nbsp;获取用户的登录令牌 <br/>
     * 步骤&nbsp;: <br/>
     * 1.&nbsp;认证用户 <br/>
     * 2.&nbsp;创建令牌 <br/>
     * 3.&nbsp;如果用户存在当前卡片，直接返回；否则，创建新用户卡片并更新用户当前令牌 <br/>
     * 4.&nbsp;如果用户没有rsToken，则创建rsToken并返回；否则，直接返回 <br/>
     * 5.&nbsp;返回创建的令牌 <br/>
     * @param header <br/><br/>
     * @param query <br/><br/>
     * @throws ServiceException <br/>
     * TOKENSERVICE_GET_201 : <br/>&nbsp&nbsp&nbsp&nbsp异常类型 : 业务流程异常<br/>&nbsp&nbsp&nbsp&nbsp异常业务 : 认证用户<br/>&nbsp&nbsp&nbsp&nbsp异常描述 : 用户不存在或密码不匹配<br/>
     * @see TokenModel result <br/>
     */ 
    //endregion
    //region 说明 : get
    //获取用户的登录令牌
    //简介 : 获取用户的登录令牌
    //步骤 :
    //1. 认证用户
    //2. 创建令牌
    //3. 如果用户存在当前卡片，直接返回；否则，创建新用户卡片并更新用户当前令牌
    //4. 如果用户没有rsToken，则创建rsToken并返回；否则，直接返回
    //5. 返回创建的令牌
    //endregion
    //region 参数 : get
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user-name", value = "用户名",required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "password", value = "密码",required = true, dataType = "string", paramType = "header"),
    })
    //endregion
    //region 请求 : get
    @RequestMapping(value = "/tokens", method = RequestMethod.GET)
    //endregion
    public TokenModel get(Map<String, String> header, Map<String, Object> query) throws ServiceException {
        String password = header.get("_password");
        if (StringUtils.isEmpty(password)) {
            throw new ServiceException(Login_ErrorsEnum.TOKENSERVICE_GET_201);
        }
        String userName = HzhrTypeUtil.object2string(header.get("_user-name"));
        if (StringUtils.isEmpty(userName)) {
            throw new ServiceException(Login_ErrorsEnum.TOKENSERVICE_GET_201);
        }

        /* 认证用户 */
        UserEntityExample userEntityExample = new UserEntityExample();
        userEntityExample.createCriteria().andUserNameEqualTo(userName).andPasswordEqualTo(password).andIsValidEqualTo(CommonOptions.YES_NO.YES);
        List<UserEntity> userEntities = userEntityMapper.selectByExample(userEntityExample);
        if (userEntities.size() == 0) {
            throw new ServiceException(Login_ErrorsEnum.TOKENSERVICE_GET_201);
        }
        UserEntity user_1 = userEntities.get(0);

        /* 创建令牌 */
        String token_1 = "cqgas-" + HzhrStringUtils.getGUID();

        /* 如果用户存在当前卡片，直接返回 */
        String currentToken = user_1.getCurrentToken();
        UserCardEntity userCardEntity = userCardDao.selectByToken(currentToken);
        if (userCardEntity == null) {
            /* 创建新用户卡片 */
            userCardEntity = new UserCardEntity();
            userCardEntity.setToken(token_1);
            userCardEntity.setUserId(user_1.getId());
            userCardEntity.setUserCode(user_1.getUserCode());
            userCardEntity.setUserName(user_1.getUserName());
            userCardEntity.setCompanyId(user_1.getCompanyId());
            userCardEntity.setDeptId(user_1.getDeptId());
            userCardEntity.setType(user_1.getType());
            userCardEntity.setExpireTime(HzhrDateUtil.addTime(new Date(), 120, Calendar.MINUTE).getTime());
            userCardDao.insert(userCardEntity);

            /* 更新用户的当前令牌 */
            user_1.setCurrentToken(token_1);
            userEntityMapper.updateByPrimaryKey(user_1);
        }

        /* 如果用户没有rsToken，则创建rsToken并返回 */
        String rsToken = HzhrTypeUtil.object2string(redisUtil.get("rsToken:" + user_1.getUserName()));
        if (StringUtils.isEmpty(rsToken)) {
            rsToken = "cqgas-" + HzhrStringUtils.getGUID();
            redisUtil.set("rsToken:" + user_1.getUserName(), rsToken);
        }
        redisUtil.hmSet(rsToken, "user-name", userName);
        redisUtil.hmSet(rsToken, "password", password);

        /* 返回创建的令牌 */
        TokenModel tokenModel = new TokenModel();
        tokenModel.setRsToken(rsToken);
        tokenModel.setToken(userCardEntity.getToken());
        tokenModel.setExpireTime(userCardEntity.getExpireTime());
        tokenModel.setIsNewUser(user_1.getIsNewUser());
        tokenModel.setUserType(user_1.getType());
        return tokenModel;
    }
}
























































































































































































































